﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ThreadSyncron.Utils;

namespace ThreadSyncron
{
	public partial class FMain : Form
	{
		private delegate void ThreadEndAction(IIOActionParameters inparams);

		public FMain()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			string threaName = (TSPool.Instance.GetThreadsCount() + 1).ToString();
			textBox1.Text += @"Start " + threaName + Environment.NewLine;
			Parrams pars = new Parrams();
			pars.AddParam("Test string " +threaName);
			TSPool.Instance.AddThread(MakeAction, threaName, this.EndAction, pars);
		}

		private void EndAction(IIOActionParameters inparams)
		{
			if(this.InvokeRequired)
			{
				this.BeginInvoke(new ThreadEndAction(this.EndAction), inparams);
			}
			else
			{
				string s = inparams.GetParam(0) as string;
				if (s == null) return;
				this.textBox1.Text+= Environment.NewLine+ s;
			}
		}

		private IIOActionParameters MakeAction(IIOActionParameters inparams)
		{
			Thread.Sleep(5500);
			string s = inparams.GetParam(0) as string;
			if (s == null) return null;
			Parrams outPars = new Parrams();
			outPars.AddParam(string.Format("Thread {0} returned", s));
			return outPars;
		}

	}

	public class Parrams : IIOActionParameters
	{
		private IList<string> Params;

		public Parrams()
		{
			Params = new List<string>();
		}

		public int AddParam(object value)
		{
			string s = value as string;
			if (s == null) return -1;
			Params.Add(s);
			return Params.Count - 1;
		}

		public object GetParam(int pos)
		{
			return pos >= 0 ? Params[pos] : null;
		}
	}

}
